﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;
using System.Web.Http.ModelBinding;
using GC_MU.Site.Api.Models;

namespace GC_MU.Site.Api.Attributes
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
	public sealed class ValidationActionFilterAttribute : ActionFilterAttribute
	{
		public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
		{
			if (!actionExecutedContext.ActionContext.ModelState.IsValid)
				actionExecutedContext.Response = GetResponse(actionExecutedContext.Request, actionExecutedContext.ActionContext.ModelState);
		}

		private static HttpResponseMessage GetResponse(HttpRequestMessage request, IEnumerable<KeyValuePair<string, ModelState>> modelState)
		{
			var errorMessage = modelState
				.Where(s => s.Value.Errors.Count > 0)
				.SelectMany(s => s.Value.Errors)
				.Select(o => o.ErrorMessage).FirstOrDefault();

			if (string.IsNullOrWhiteSpace(errorMessage))
				errorMessage = "Bad request.";

			return request.CreateResponse(HttpStatusCode.BadRequest, new ResponseErrorModel
			{
				Meta = new MetaModel
				{
					Code = HttpStatusCode.BadRequest
				},
				Error = new ErrorModel
				{
					Message = errorMessage
				},
			});
		}
	}
}